package sddz.foodmanage.fragment;


import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bigkoo.pickerview.TimePickerView;
import com.bigkoo.pickerview.listener.OnDismissListener;
import com.google.gson.Gson;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.header.progresslayout.ProgressLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.Request;
import sddz.foodmanage.R;
import sddz.foodmanage.activity.LoginActivity;
import sddz.foodmanage.activity.MainNewActivity;
import sddz.foodmanage.activity.WaitCheckActivity;
import sddz.foodmanage.activity.WaitCommentActivity;
import sddz.foodmanage.adapter.UniversalAdapter;
import sddz.foodmanage.adapter.UniversalViewHolder;
import sddz.foodmanage.base.BaseFragment;
import sddz.foodmanage.base.BasePageFragment;
import sddz.foodmanage.model.WaitListBean;
import sddz.foodmanage.utils.API;
import sddz.foodmanage.utils.HttpUtils;
import sddz.foodmanage.utils.SpfUtils;

/**
 * @Date:2019/7/10
 * @Author:lbb 中队的待核实，待评论页面（订单号，时间 金额）
 * 供应商的待配送（中队 时间 金额）
 */
public class WaitFragment extends BasePageFragment {

    @BindView(R.id.wait_listView)
    ListView waitListView;
    Unbinder unbinder;
    @BindView(R.id.tv_zanwu)
    TextView tvZanwu;
    //==============================================================================================
    @BindView(R.id.rl_check_by_time)
    RelativeLayout rlCheckByTime;
    @BindView(R.id.tv_delivertime)
    TextView tvDeliverTime;
    @BindView(R.id.tv_query)
    TextView tvQuery;
    private String deliverTime;
    private TimePickerView pvDeliveryTime;      //配送时间选择器
    private boolean clic_cancle = false;        //用于标识是否直接点击的时间选择器中的全部显示按钮
    //==============================================================================================

    private int waitstatus;
    private List<WaitListBean.DataBean> goodslist = new ArrayList<>();
    private List<WaitListBean.DataBean> query_goodslist = new ArrayList<>();
    private UniversalAdapter adapter;
    private UniversalAdapter query_adapter;
    String key;

    @SuppressLint("HandlerLeak")
    private Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                tvZanwu.setVisibility(View.GONE);
                waitListView.setAdapter(adapter);
            }
        }
    };

    public WaitFragment() {
        // Required empty public constructor
    }


    public static WaitFragment newInstance(String stype) {

        Bundle args = new Bundle();
        args.putString("types", stype);
        WaitFragment fragment = new WaitFragment();
        fragment.setArguments(args);

        return fragment;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        Log.e("onHiddenChanged", "onHiddenChanged" + "");
        if (!hidden) {
//            getwait(waitstatus);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_wait, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView();
        initData();
        initListener();
        view.setClickable(true);
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        initData();
    }

    private void initData() {
        /**
         * 中队的待核实(1)，待评论页面(2)（订单号，时间 金额）后来添加的自采页面
         * 供应商的待配送（(3)中队 时间 金额）
         * 待配送 2 待核实 3 待评论 4
         *
         */
        key = (String) getArguments().get("types");
        Log.e("types", key);
        if (key.equals("待核实")) {
            waitstatus = 3;
            fetchData();
            rlCheckByTime.setVisibility(View.GONE);//将时间选择与查询按钮隐藏
//            getwait(waitstatus);
        } else if (key.equals("待评论")) {
            waitstatus = 4;
            fetchData();
            rlCheckByTime.setVisibility(View.GONE);//将时间选择与查询按钮隐藏
//            getwait(waitstatus);
        } else if (key.equals("待配送")) {
            waitstatus = 2;
            fetchData();
            rlCheckByTime.setVisibility(View.VISIBLE);//将时间选择与查询按钮显示出来
//            getwait(waitstatus);
        }

        //初始化时间
        deliverTime = "请选择";
        tvDeliverTime.setText(deliverTime);
/*
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String sim = dateFormat.format(date);
        deliverTime = sim;
        tvDeliverTime.setText(sim);
*/

        //时间选择器
        pvDeliveryTime = new TimePickerView.Builder(getActivity(), new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                String date1 = new SimpleDateFormat("yyyy-MM-dd").format(date);
                deliverTime = date1;
                tvDeliverTime.setText(deliverTime);
                clic_cancle = true;//点击了确定按钮以后标识一下 在时间选择器消失以后再赋值为false
            }
        })
                .setType(new boolean[]{true, true, true, false, false, false})
                .setCancelText("全部显示")
                .setCancelColor(getResources().getColor(R.color.title_color))
                .setSubmitColor(getResources().getColor(R.color.title_color))
                .setOutSideCancelable(false).isDialog(true)
                .build();

        pvDeliveryTime.setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss(Object o) {
                if (!clic_cancle) {//如果没有点击了确定按钮
                    deliverTime = "请选择";
                    tvDeliverTime.setText(deliverTime);
                    //给Handler发送消息更新ListView
                    Message message = myHandler.obtainMessage();
                    message.what = 1;
                    myHandler.sendMessage(message);
                }
                clic_cancle = false;//点击了确定按钮以后标识一下 在时间选择器消失以后再赋值为false
            }
        });
        pvDeliveryTime.setDate(Calendar.getInstance());

    }


    private void initView() {
//        waitTrl.setOnRefreshListener(new RefreshListenerAdapter() {
//            @Override
//            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
//                super.onRefresh(refreshLayout);
//                getwait(waitstatus);
//                waitTrl.finishRefreshing();
//            }
//
//            @Override
//            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
//                super.onLoadMore(refreshLayout);
//                waitTrl.finishLoadmore();
//            }
//        });


        adapter = new UniversalAdapter<WaitListBean.DataBean>(mActivity, goodslist, R.layout.item_wait) {
            @Override
            public void convert(UniversalViewHolder holder, int position, WaitListBean.DataBean newsBean) {
                if (key.equals("待配送")) {
                    holder.setText(R.id.tv_wait_orderid, newsBean.getDetachment().getName());
                } else {
                    holder.setText(R.id.tv_wait_orderid, newsBean.getNumber());
                }
                holder.setText(R.id.tv_wait_time, newsBean.getUpdated_at());
                holder.setText(R.id.tv_money, newsBean.getTotal_price() + "" + "元");
                holder.setText(R.id.tv_delivery_time, newsBean.getDelivery_time());
                if(key.equals("自采")){
                    //如果是自采订单 就不显示送货时间
                    holder.setText(R.id.tv_delivery_time, "");
                }
            }
        };
        waitListView.setAdapter(adapter);
//        ProgressLayout progressLayout = new ProgressLayout(mActivity);
//        progressLayout.setColorSchemeResources(R.color.colorPrimary);
//        waitTrl.setHeaderView(progressLayout);
    }

    private void initListener() {
        waitListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (key.equals("待核实")) {
                    MainNewActivity.a = 2;
                    Intent intent = new Intent(mActivity, WaitCheckActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("data", goodslist.get(position));
                    intent.putExtras(bundle);
                    startActivity(intent);
                } else if (key.equals("待评论")) {
                    Intent intent = new Intent(mActivity, WaitCommentActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("data", goodslist.get(position));
                    bundle.putString("status", "待评论");
                    intent.putExtras(bundle);
                    startActivity(intent);
                } else if (key.equals("待配送")) {
                    Intent intent = new Intent(mActivity, WaitCommentActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("data", goodslist.get(position));
                    bundle.putString("status", "待配送");
                    intent.putExtras(bundle);
                    startActivity(intent);
                }

            }
        });
    }

    //获取待核实待评论数据 type 待配送 2 待核实 3 待评论 4
    private void getwait(final int type) {
        Map<String, Integer> map = new HashMap<>();
        map.put("type", type);
        baseDialog.show();
        HttpUtils.getInstance().POST(mActivity, API.getwaitlist, JSON.toJSONString(map), SpfUtils.gettoken(mActivity), new HttpUtils.OnOkHttpCallback() {
            @Override
            public void onSuccess(String body) {
                baseDialog.dismiss();
                Log.e("获取的" + key + type, body);
                if (!TextUtils.isEmpty(body)) {
                    try {
                        JSONObject jsonObject = new JSONObject(body);
                        int code = jsonObject.optInt("status_code");
//                        if (!jsonObject.optString("message").equals("")) {
//                            show(jsonObject.optString("message"));
//                        }
                        if (code == 200) {
                            WaitListBean waitListBean = new Gson().fromJson(body, WaitListBean.class);
                            if (waitListBean.getData().size() > 0) {
                                waitListView.setVisibility(View.VISIBLE);
                                tvZanwu.setVisibility(View.GONE);

                                if (goodslist != null) {
                                    goodslist.clear();
                                }
                                goodslist.addAll(waitListBean.getData());
                                Log.e("goodslist", goodslist.size() + "");
                                if (adapter == null) {
                                    initView();
                                }
                                adapter.notifyDataSetChanged();
                            } else {
                                waitListView.setVisibility(View.GONE);
                                tvZanwu.setVisibility(View.VISIBLE);
                                adapter.notifyDataSetChanged();
                            }


                        } else if (code == 210) {
                            String token = jsonObject.optJSONObject("data").optString("token");
                            SpfUtils.savetoken(mActivity, token);
                            getwait(waitstatus);
                        } else if (code == 401) {
                            SpfUtils.setLogin(mActivity, false);
                            startActivity(new Intent(mActivity, LoginActivity.class));
                            mActivity.finish();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

            }

            @Override
            public void onError(Request error, Exception e) {
                baseDialog.dismiss();
                show("访问数据失败，请稍后重试");
            }
        });

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void fetchData() {
        getwait(waitstatus);
    }

    @OnClick({R.id.tv_delivertime, R.id.tv_query})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_delivertime://选择时间
                pvDeliveryTime.show();
                break;
            case R.id.tv_query://查询

                if(!tvDeliverTime.getText().equals("请选择")){

                    if (query_goodslist != null) {
                        query_goodslist.clear();
                    }
                    for (int i = 0; i < goodslist.size(); i++) {
                        //判断送货时间是不是一样
                        if (goodslist.get(i).getDelivery_time().equals(tvDeliverTime.getText())) {
                            query_goodslist.add(goodslist.get(i));
                        }
                    }
                    if(0>=query_goodslist.size()){
                        //如果查询结果里边没有数据
                        tvZanwu.setVisibility(View.VISIBLE);
                    }else{
                        tvZanwu.setVisibility(View.GONE);
                    }
                    query_adapter = new UniversalAdapter<WaitListBean.DataBean>(mActivity, query_goodslist, R.layout.item_wait) {
                        @Override
                        public void convert(UniversalViewHolder holder, int position, WaitListBean.DataBean newsBean) {
                            if (key.equals("待配送")) {
                                holder.setText(R.id.tv_wait_orderid, newsBean.getDetachment().getName());
                            } else {
                                holder.setText(R.id.tv_wait_orderid, newsBean.getNumber());
                            }
                            holder.setText(R.id.tv_wait_time, newsBean.getUpdated_at());
                            holder.setText(R.id.tv_money, newsBean.getTotal_price() + "" + "元");
                            holder.setText(R.id.tv_delivery_time, newsBean.getDelivery_time());
                        }
                    };
                    waitListView.setAdapter(query_adapter);
                }


                break;
        }
    }


}